package com.leonzx.base.service.system;

import com.leonzx.base.dao.system.OrdersCharRootDAO;
import com.leonzx.base.dao.system.OrdersDAO;
import com.leonzx.base.entity.system.Orders;
import com.leonzx.base.entity.system.OrdersChatRoot;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.service.file.FileUploadService;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.SQLUtils;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:张勇
 * @Description:
 * @Date: 2018-06-08 15:13
 */
@Service
public class OrdersService extends BaseService {
    @Autowired
    private OrdersDAO ordersDAO;
    @Autowired
    private OrdersCharRootDAO ordersCharRootDAO;
    @Autowired
    private FileUploadService fileUploadService;

    public List<Orders> getAllBaseOrders(Orders orders) {
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(orders.getName())) {
            criteria.andLike("name", SQLUtils.like(orders.getName()));
        }
        if (StringUtils.isNotBlank(orders.getNumber())) {
            criteria.andLike("number", SQLUtils.like(orders.getNumber()));
        }
        if (orders.getState() != null) {
            criteria.andEqualTo("state", orders.getState());
        }
        return ordersDAO.selectByExample(example);
    }

    public void saveGroupMessage(String ordersNumber, String content, String ryId) {
        OrdersChatRoot ordersChatRoot = new OrdersChatRoot();
        ordersChatRoot.setOrdes_namber(ordersNumber);
        OrdersChatRoot ordersChatRootOnle = ordersCharRootDAO.selectOne(ordersChatRoot);
        if (ordersChatRootOnle != null) {
            ordersChatRootOnle.setContent(content);
            ordersCharRootDAO.updateByPrimaryKeySelective(ordersChatRootOnle);
        } else {
            ordersChatRoot.setId(UUIDUtils.getUUID());
            ordersChatRoot.setOrdes_namber(ordersNumber);
            ordersChatRoot.setContent(content);
            ordersChatRoot.setCreateTime(new Date());
            ordersChatRoot.setCreateUserId(ryId);
            ordersCharRootDAO.insert(ordersChatRoot);
        }
    }

    public Map<String, Object> uploadImg(String number, MultipartFile img, HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashedMap();
        String oldName = img.getOriginalFilename();
        int index = oldName.lastIndexOf(".");
        String name = UUIDUtils.getUUID() + oldName.substring(index); //新文件名
        String path = "static" + File.separator + "files" + File.separator + Constants.FILE_TYPE_IMG_JIM + File.separator + number;
        String imgUrl = path + "/" + name;
        fileUploadService.upload(img, imgUrl);
        Map<String, Object> urlMap = new HashedMap();
        String src = request.getContextPath() + "/orders/getImg?key=" + imgUrl.replaceAll("\\\\", "/");
        urlMap.put("src", src);
        result.put("data", urlMap);
        return result;
    }


    public Map<String, Object> uploadVideo(String number, MultipartFile img) throws IOException {
        Map<String, Object> result = new HashedMap();
        String oldName = img.getOriginalFilename();
        int index = oldName.lastIndexOf(".");
        String newName = UUIDUtils.getUUID() + oldName.substring(index); //新文件名
        String firlUrl = Constants.FILE_TYPE_VIDEO_JIM;
        String url = "static" + File.separator + "files" + File.separator + firlUrl + File.separator + number + File.separator + newName;
        fileUploadService.upload(img, url);
        String bclj = "static" + File.separator + "files" + File.separator + Constants.FILE_TYPE_VIDEO_JIM + File.separator + number;
        String videoUrl = fileUploadService.getUrlByKey(bclj + "/" + newName);
        result.put("videoUrl", videoUrl.replaceAll("\\\\", "/"));
        return result;
    }

    public InputStream selImg(String path, String name) {
        String url = path + "/" + name;
        InputStream inputStream = fileUploadService.download(url);
        return inputStream;

    }

    public void getInputStream(String key, HttpServletResponse resp) throws IOException {
        InputStream inputStream = fileUploadService.download(key);
        byte[] tempbytes = new byte[100];
        int byteread = 0;
        OutputStream out = resp.getOutputStream();
        while ((byteread = inputStream.read(tempbytes)) != -1) {
            out.write(tempbytes, 0, byteread);
        }
        // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
        out.close();
        inputStream.close();
    }


    public String findIdByNumber(String number) {
        return ordersDAO.findIdByNumber(number);
    }

    public Map<String, Object> uploadFile(String number, MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = new HashedMap();
        String oldName = file.getOriginalFilename();
        int index = oldName.lastIndexOf(".");
        String name = UUIDUtils.getUUID() + oldName.substring(index); //新文件名
        String path = "static" + File.separator + "files" + File.separator + Constants.FILE_TYPE_EMAIL_FILE + File.separator + number;
        String imgUrl = path + "/" + name;
        fileUploadService.upload(file, imgUrl);
        Map<String, Object> urlMap = new HashedMap();
        String src = fileUploadService.getUrlByKey(path + "/" + name);
        urlMap.put("src", src.replaceAll("\\\\", "/"));
        result.put("data", urlMap);
        return result;
    }
}
